angular.module('myapp.BthSevice', [])

    .factory('BthSevice', function ($rootScope, $cordovaBluetoothLE, $cordovaToast, $timeout, $interval, PopupService, $state, $http, $myconfig) {
        // Might use a resource here that returns a JSON array

        // Some fake testing data
             //判定当前设备类型是ios还是android
        var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

        var devices = {};
        var getBLEStatusInterval = null;
        var getCurrentData = [
            0x8b, //起始码
            0x01,  //查询当前数据
            0xff,
            0xff,
            0xff,
            0xff,
            0xff,
            0xff,
            0xbf //结束码
        ];
        return {
            scanned: false, // 是否扫描过
            devices: devices,
            scanDevices: {},
            address: null,
            // service: 'FFF0',
            service: 'FFE0',
            characteristic: 'FFE1',
            // characteristic: 'FFF3',
            initialize: function () { // 初始化
                var _this = this;
                var params = {
                    request: true,
                    //restoreKey: "bluetooth-test-app"
                };
                // console.log("Initialize : " + JSON.stringify(params));

                //初始化
                $cordovaBluetoothLE.initialize(params).then(null, function (obj) {
                    // console.log("Initialize Error : " + JSON.stringify(obj)); //Should only happen when testing in browser
                }, function (obj) {
                        _this.hasPermission(function (res) {
                            if (res.hasPermission) { // 判断权限
                                _this.initConnectSevice(); // 直接尝试连接设备
                            } else {
                                if(isiOS){
                                    if(obj.status == 'enabled'){
                                                _this.initConnectSevice(); // 直接尝试连接设备
                                    }else{
                                         console.log('提示用户开启蓝牙');
                                         $state.go('app.guidance');
                                    }
                                }else{
                                    _this.requestPermission(function (res) {
                                        if (res.requestPermission) { // 用户允许
                                            _this.initConnectSevice(); // 直接尝试连接设备
                                        }
                                    }); //请求权限
                                }

                            }
                        });
                    // }
                });

            },
            initConnectSevice: function () { // 连接设备
                var _this = this;
                var addr = localStorage.getItem('addr'); //获取本地存储的设备地址
                var hasDevice = false; //未搜索到可连接的设备
                if (addr) {
                    $cordovaToast.showShortCenter('正在连接...');
                    // alert('正在连接');
                    _this.isScanning(function (res) { // 先判断扫描状态，停止后再扫描
                        _this.isConnect(function (status) { // 是否是连接状态，关闭后扫描
                            if (res.isScanning) {
                                // console.log('停止后扫描........');
                                _this.stopScan();
                            }
                            if (status) {
                                // console.log('连接中先断开........');
                                _this.closeConn(_this.address);
                            }
                            $timeout(function () {
                                /*_this.startScan(function (res) {

                                    if (res.status == 'ok') { // 已经扫描完成
                                        for (address in _this.devices) {
                                            if (address == addr) { // 说明当前存储的设备已经运行
                                                hasDevice = true;*/

                                                _this.connect(addr, function (res) {
                                                    if (res.success) { // 连接成功
                                                        // alert('连接成功');
                                                        _this.devices = JSON.parse(localStorage.getItem(addr));
                                                        _this.address = addr;
                                                        // console.log('设备已经连接过......');
                                                        // console.log(_this.devices);

                                                       $timeout(function () {
                                                           _this.getLastSPA();
                                                       }, 3000);

                                                        /*if($rootScope.isKeepConnect == false){ //说明没有检查过
                                                            _this.checkState();
                                                        }*/

                                                    } else { // 失败提示重试
                                                        // $cordovaToast.showShortCenter('设备连接失败');
                                                        // $rootScope.$broadcast('sendToMenu', 'off');
                                                    }
                                                });
                            }, 600);

                        });

                    });

                }else{
                    // $rootScope.$broadcast('BthConnect', 'failed'); // 广播事件连接失败
                    // alert('连接失败');
                    _this.startScan(function (res) {
                        console.log(res);
                        switch (res.status) {
                            case 'ok':
                                break;
                            case 'timeout':
                                $rootScope.$broadcast('BthConnect', 'failed'); // 广播事件连接失败
                                break;
                            default:
                                $cordovaToast.showShortCenter('设备连接失败');
                        }
                    });
                }
            },
            getLastSPA: function () {
                var _this = this;
                // alert(1111111111);
                var ble_name = JSON.parse(localStorage.getItem(this.address)).name;
                var lastSPAEnd = localStorage.getItem('lastSPAEnd');
                console.log('lastSPAEnd');
                console.log(lastSPAEnd);
                if(!lastSPAEnd){
                    $interval.cancel(getBLEStatusInterval);
                    getBLEStatusInterval = $interval(function () {
                        _this.getBLEStatus();
                    }, 2000);
                    return;
                }
                lastSPAEnd = JSON.parse(lastSPAEnd);
                var _this = this;
                if(ble_name.indexOf('QMK-') > -1 && !lastSPAEnd.status){
                    // localStorage.setItem('lastSPAEnd', JSON.stringify({status: true})); //设置为完成状态
                    var data = [
                        0x8b, //起始码
                        0x02,  //查询当前数据
                        0xff,
                        0xff,
                        0xff,
                        0xff,
                        0xff,
                        0xff,
                        0xbf //结束码
                    ];

                    var clear_data = [
                        0x8a, //起始码
                        0x00,  //查询当前数据
                        0x00,
                        0x00,
                        0x00,
                        0x00,
                        0x00,
                        0x00,
                        0x00 //结束码
                    ]
                    var ints = new Uint8Array(data, data.length);
                    var params = {
                        address: this.address,
                        service: this.service,
                        characteristic: this.characteristic,
                        value: $cordovaBluetoothLE.bytesToEncodedString(ints),

                        // value: $cordovaBluetoothLE.bytesToEncodedString($cordovaBluetoothLE.stringToBytes("Hello World")),
                        timeout: 5000
                    };

                    var clear_params = {
                        address: this.address,
                        service: this.service,
                        characteristic: this.characteristic,
                        value: $cordovaBluetoothLE.bytesToEncodedString(new Uint8Array(clear_data, clear_data.length)),

                        // value: $cordovaBluetoothLE.bytesToEncodedString($cordovaBluetoothLE.stringToBytes("Hello World")),
                        timeout: 5000
                    }

                    var params1 = {
                        address: this.address,
                        service: this.service,
                        characteristic: this.characteristic,
                        // descriptor: '2901'
                    };
                    if(isiOS){
                        params.type = 'noResponse'
                    }

                    console.log("getLastSPA Write : " + JSON.stringify(params) + ' ' + new Date().getTime());
                    // $cordovaBluetoothLE.write(params).then(function (obj) {
                    $cordovaBluetoothLE.writeQ(params).then(function (obj) {
                        console.log("getLastSPA Write Success : " + JSON.stringify(obj));

                        $cordovaBluetoothLE.read(params1).then(function (obj1) { //读取数据
                            console.log("getLastSPA read Success : " + JSON.stringify(obj1));
                            var bytes = bluetoothle.encodedStringToBytes(obj1.value);
                            // var string = bluetoothle.bytesToString(bytes);
                            console.log('读取上次保养数据。。。。。。。。。。。');
                            console.log(bytes);
                            // console.log(string);

                            $interval.cancel(getBLEStatusInterval);
                            getBLEStatusInterval = $interval(function () {
                                _this.getBLEStatus();
                            }, 2000);


                            if(bytes[0] == 0x8d){ //反馈指令
                                var minutes = parseInt(bytes[4], 10); //分钟
                                var seconds = parseInt(bytes[5], 10); //分钟
                                console.log('上次保养%s分钟%s秒', minutes, seconds);

                                // if(lastSPAEnd.type == 'nose'){
                                // }else if(lastSPAEnd.type == 'face'){
                                // }

                                var SPAState = (lastSPAEnd.typeTime == (minutes * 60 + seconds) ? 1 : 0)
                                $http.post($myconfig.api.base_host + '/users/maintain', {
                                    "user_id": lastSPAEnd.user_id,
                                    "dev_name": lastSPAEnd.dev_name,
                                    "mode": lastSPAEnd.mode,
                                    "duration": minutes * 60 + seconds,
                                    "state": SPAState,
                                    "createtime": new Date()
                                }).then(function(res) {
                                    console.log('保存上次保养数据：');
                                    console.log(res.data.data);
                                    var integral = res.data.integral; //本次健康豆
                                    // $interval.cancel(secTime);
                                    $http.get($myconfig.api.base_host + '/physicallogs/finsh?user_id=' + lastSPAEnd.user_id + '&mode=' + lastSPAEnd.mode + '&dev_name=' + lastSPAEnd.dev_name)
                                        .then(function(res) {
                                            console.log('更新用户保养数据：');
                                            console.log(res.data.data);
                                            res.data.data.duration = ((res.data.data.duration) / 60).toFixed(1);
                                            res.data.data.totle_duration = ((res.data.data.totle_duration) / 60).toFixed(1);
                                            res.data.data.num = integral; //健康豆
                                            $rootScope.finsh = res.data.data;
                                            console.log($rootScope.finsh);
                                            $http.get($myconfig.api.base_host + '/users/user_info?mobile=' + $rootScope._RootUser.mobile)
                                                .then(function(res) {
                                                    if (res.data.success) {
                                                        localStorage.removeItem('lastSPAEnd');
                                                        localStorage.setItem('user', JSON.stringify(res.data.data));
                                                    }

                                                    //清除上次的保养记录
                                                    $cordovaBluetoothLE.writeQ(clear_params).then(function (obj1) {
                                                        console.log("getLastSPA clear Success : " + JSON.stringify(obj1));

                                                        // _this.getLastSPA();
                                                    }, function (obj) {
                                                        console.log("getLastSPA clear Error : " + JSON.stringify(obj1));
                                                    });

                                                    $state.go('app.CoryzaEnd', {
                                                        type: lastSPAEnd.mode
                                                    });
                                                });
                                        });
                                });



                            }else { //反馈指令

                                console.log('不是保养完成的数据，看是否保养中...');

                                var current_ints = new Uint8Array(getCurrentData, getCurrentData.length);
                                var current_params = {
                                    address: _this.address,
                                    service: _this.service,
                                    characteristic: _this.characteristic,
                                    value: $cordovaBluetoothLE.bytesToEncodedString(current_ints),

                                    // value: $cordovaBluetoothLE.bytesToEncodedString($cordovaBluetoothLE.stringToBytes("Hello World")),
                                    timeout: 5000
                                };

                                if(isiOS){
                                    current_params.type = 'noResponse'
                                }

                                console.log("Write : " + JSON.stringify(current_params) + ' ' + new Date().getTime());
                                // $cordovaBluetoothLE.write(params).then(function (obj) {
                                $cordovaBluetoothLE.writeQ(current_params).then(function (obj) {
                                    console.log("Write Success : " + JSON.stringify(obj));

                                    $cordovaBluetoothLE.read(params1).then(function (obj1) { //读取数据
                                        console.log("read Success : " + JSON.stringify(obj1));
                                        var bytes = bluetoothle.encodedStringToBytes(obj1.value);
                                        // var string = bluetoothle.bytesToString(bytes);
                                        console.log('读取当前保养数据。。。。。。。。。。。');
                                        console.log(bytes);

                                        if(bytes[0] == 0x8C){
                                            var minutes = parseInt(bytes[4], 10); //分钟
                                            var seconds = parseInt(bytes[5], 10); //秒钟
                                            console.log('当前保养到了%s分钟%s秒', minutes, seconds);
                                            if(minutes != 0 || seconds !=0){ //分钟不为0 或者秒钟不为0 说明在保养中
                                                var sum_seconds = minutes * 60 + (seconds - 1); //剩余的保养时间
                                                $rootScope.start = true; //保养中
                                                var typeTime = lastSPAEnd.typeTime; //保养总时间
                                                var spa_type = lastSPAEnd.spa_type; //保养类型

                                                $rootScope.$broadcast('restoreSPA', {
                                                    type: lastSPAEnd.type, //保养分类
                                                    typeTime: typeTime,
                                                    spa_type: spa_type, //保养类型
                                                    stateText: lastSPAEnd.stateText,
                                                    ts: sum_seconds,
                                                    mode: lastSPAEnd.mode
                                                });
                                            }
                                        }

                                        // console.log(string);
                                    }, function (error) {
                                        console.log("read Error : " + JSON.stringify(error));
                                    });

                                }, function (obj) {
                                    console.log("Write Error : " + JSON.stringify(obj));

                                });

                            }

                        }, function (error) {
                            console.log("getLastSPA read Error : " + JSON.stringify(error));
                        });

                    }, function (obj) {
                        console.log("getLastSPA Write Error : " + JSON.stringify(obj));
                    });

                }
            },
            checkState: function () {
                var addr = localStorage.getItem('addr'); //获取本地存储的设备地址
                $rootScope.isKeepConnect = true; //记录连接状态
                var _this = this;
                $rootScope.checkStateInterval = $interval(function () {
                    _this.isConnect(function (status) { // 是否是连接状态，关闭后扫描
                        console.log('当前连接状态..........');
                        console.log(status);
                        if (!status && $rootScope.isKeepConnect) { //如果没有连接并且保持链接的标志为true，尝试连接设备
                            console.log('去重连..........');
                            // _this.initialize();

                            _this.connect(addr, function (res) {
                                if (res.success) { // 连接成功
                                    _this.devices = JSON.parse(localStorage.getItem(addr));
                                    _this.address = addr;

                                } else { // 失败提示重试
                                    console.log('去重连失败..........');
                                }
                            });

                        }
                    });
                }, 5000);

                bluetoothle.initializePeripheral(function (result) {
                    console.log('initializePeripheral......');
                    console.log(result);
                }, function (error) {
                    console.log('initializePeripheral......');
                    console.log(error);
                }, {
                    "status": "disconnected",
                    "address": addr
                });

            },
            enable: function () { // 开启蓝牙
                // console.log("Enable");

                $cordovaBluetoothLE.enable().then(null, function (obj) {
                    // console.log("Enable Error : " + JSON.stringify(obj));
                });
            },
            disable: function () { // 关闭蓝牙
                // console.log("Disable");

                $cordovaBluetoothLE.disable().then(null, function (obj) {
                    // console.log("Disable Error : " + JSON.stringify(obj));
                });
            },
            initbth: function (callback) {
                var _this = this;
                var params = {
                    request: true
                };
                $cordovaBluetoothLE.initialize(params).then(null, function (obj) {
                    // console.log("Initialize Error : " + JSON.stringify(obj)); //Should only happen when testing in browser
                }, function (obj) {
                    // console.log("Initialize Success : " + JSON.stringify(obj));
                    if(isiOS){

                        if(obj.status == 'enabled'){
                            callback(true);
                        }else if(obj.status != 'enabled'){
                            $state.go('app.guidance');
                        }
                    }else{

                        _this.hasPermission(function (res) {
                            if (res.hasPermission) { // 判断权限
                                console.log('已经获取权限...');
                                callback(true);
                            } else {
                                _this.requestPermission(function (res) {
                                    if (res.requestPermission) { // 用户允许
                                        console.log('权限已获取...');
                                        callback(true);
                                    }
                                }); //请求权限
                            }
                        });
                    }
                },function(obj){
                    console.log(obj);
                });
            },
            startScan: function (callback) { // 开始扫描
                var _this = this;
                _this.initbth(function (result) {
                    console.log(result);
                    if(result){
                        _this.isScanning(function (res) { // 先判断扫描状态，停止后再扫描
                            _this.isConnect(function (status) { // 是否是连接状态，关闭后扫描
                                if (status) {
                                    _this.closeConn(_this.address);
                                }
                            });
                            if (res.isScanning) {
                                // console.log('停止后扫描........');
                                _this.stopScan();
                            }
                            $timeout(function () {
                                // console.log('扫描..........');
                                var params = {
                                    services: [],
                                    allowDuplicates: false,
                                    scanTimeout: 50000
                                };

                                if (window.cordova) {
                                    params.scanMode = bluetoothle.SCAN_MODE_LOW_POWER;
                                    params.matchMode = bluetoothle.MATCH_MODE_STICKY;
                                    params.matchNum = bluetoothle.MATCH_NUM_ONE_ADVERTISEMENT;
                                    //params.callbackType = bluetoothle.CALLBACK_TYPE_FIRST_MATCH;
                                }
                                // alert("Start Scan : " + JSON.stringify(params));
                                console.log("Start Scan : " + JSON.stringify(params));

                                $cordovaBluetoothLE.startScan(params).then(function (obj) {
                                    console.log(obj);
                                    // alert(JSON.stringify(obj));
                                    // console.log("Start Scan Auto Stop : " + JSON.stringify(obj));
                                    PopupService.lanya($rootScope); //提示错误
                                    _this.stopScan();
                                    callback({
                                        status: 'timeout'
                                    });
                                }, function (obj) {
                                    // alert("Start Scan Error : " + JSON.stringify(obj));
                                    console.log("Start Scan Error : " + JSON.stringify(obj));
                                    PopupService.lanya($rootScope); //提示错误
                                    _this.stopScan();
                                    callback({
                                        status: 'error'
                                    });
                                }, function (obj) {
                                    // alert("Start Scan Success : " + JSON.stringify(obj));
                                    console.log("Start Scan Success : " + JSON.stringify(obj));
                                    /*$rootScope.res.data = JSON.stringify(obj);*/
                                    if (_this.addDevice(obj)) { // 保存服务
                                        _this.stopScan();
                                        callback({
                                            status: 'ok'
                                        });
                                    }
                                });
                            }, 1500);

                        });
                    }
                });
            },
            addDevice: function (obj) { // 添加设备
                if (obj.status == "scanStarted") {
                    return false;
                }
                /*if (this.devices[obj.address] !== undefined) {
                    return false;
                }*/
                obj.services = {};
                // alert(JSON.stringify(obj));
                if(obj.name && obj.name.indexOf('QMK') > -1){ //搜索到的蓝牙名称必须包含QMK三个字母
                    this.scanDevices[obj.address] = obj;
                }

                return true;
            },
            stopScan: function () { // 停止扫描
                // console.log("Stop Scan");
                $cordovaBluetoothLE.stopScan().then(function (obj) {
                    console.log("Stop Scan Success : " + JSON.stringify(obj));
                }, function (obj) {
                    // console.log("Stop Scan Error : " + JSON.stringify(obj));
                });
            },
            discover: function (address) { // 搜索服务
                var params = {
                    address: address,
                    timeout: 10000
                };

                // console.log("Discover : " + JSON.stringify(params));

                $cordovaBluetoothLE.discover(params).then(function (obj) {
                    console.log("Discover Success : " + JSON.stringify(obj));

                    // var device = $rootScope.devices[obj.address];
                    // var services = obj.services;

                }, function (obj) {
                    // console.log("Discover Error : " + JSON.stringify(obj));
                });
            },
            connect: function (address, callback) { // 连接蓝牙
                var _this = this;
                var params = {
                    address: address,
                    timeout: 10000
                };

                _this.address = address;


                // console.log("Connect : " + JSON.stringify(params));

                $cordovaBluetoothLE.connect(params).then(null, function (obj) {
                    // console.log("Connect Error : " + JSON.stringify(obj));
                    _this.closeConn(address); //Best practice is to close on connection error
                    $cordovaToast.showShortCenter('设备连接失败');
                    // alert('设备连接bug');
                    $rootScope.$broadcast('sendToMenu', 'off');
                    callback({
                        success: false
                    }); //连接失败
                }, function (obj) {
                    // console.log("Connect Success : " + JSON.stringify(obj));
                    _this.discover(address); // 搜索服务
                    $rootScope.connected = true;
                    $cordovaToast.showShortCenter('设备已连接');
                    // alert('设备已连接');
                    $state.go('app.home');
                    $rootScope.$broadcast('loadData', 'on');
                    $rootScope.$broadcast('sendToMenu', 'on');
                    /*$interval.cancel(getBLEStatusInterval);
                    getBLEStatusInterval = $interval(function () {
                        _this.getBLEStatus();
                    }, 2000);*/

                    callback({
                        success: true
                    });
                });
            },
            closeConn: function (address) { //关闭连接
                var params = {
                    address: address
                };

                // console.log("Close : " + JSON.stringify(params));
                if(isiOS){
                 $cordovaBluetoothLE.disconnect(params).then(
                     function(res){
                        console.log(res);
                     }
                 );
                }

                $cordovaBluetoothLE.close(params).then(function (obj) {
                    // console.log("Close Success : " + JSON.stringify(obj));
                    $rootScope.$broadcast('sendToMenu', 'off');
                }, function (obj) {
                    // console.log("Close Error : " + JSON.stringify(obj));
                });

                $interval.cancel(getBLEStatusInterval);
            },
            hasPermission: function (callback) { //是否有权限
                // console.log("Has Permission");

                $cordovaBluetoothLE.hasPermission().then(function (obj) {
                    // console.log("Has Permission Success : " + JSON.stringify(obj));
                    callback(obj);
                }, function (obj) {
                    // console.log("Has Permission Error : " + JSON.stringify(obj));
                    callback(obj);
                });
            },
            requestPermission: function (callback) { // 请求蓝牙搜索权限
                // console.log("Request Permission");

                $cordovaBluetoothLE.requestPermission().then(function (obj) {
                    // console.log("Request Permission Success : " + JSON.stringify(obj));
                    callback(obj);
                }, function (obj) {
                    // console.log("Request Permission Error : " + JSON.stringify(obj));
                    callback(obj);
                });
            },
            write: function (valuesArr) { // 写数据
                console.log('写数据到蓝牙控制器......');
                console.log(valuesArr);
                if(valuesArr.length == 0){
                    return;
                }
                var time = 100;
                var _this = this;
                valuesArr.forEach(function (values) {
                    //Set this to something higher to verify queueing on read/write
                    var count = 1;
                    // var data = [0x7e, 0x04, 0x01, 0x40, 0xff, 0xff, 0xff, 0x00, 0xef];
                    var ints = new Uint8Array(values, values.length);

                    // $interval(function() {
                    var params = {
                        address: _this.address,
                        service: _this.service,
                        characteristic: _this.characteristic,
                        value: $cordovaBluetoothLE.bytesToEncodedString(ints),

                        // value: $cordovaBluetoothLE.bytesToEncodedString($cordovaBluetoothLE.stringToBytes("Hello World")),
                        timeout: 5000
                    };
                    if(isiOS){
                        params.type = 'noResponse'
                    }

                    $timeout(function () {
                        console.log("Write : " + JSON.stringify(params) + ' ' + new Date().getTime());
                        // $cordovaBluetoothLE.write(params).then(function (obj) {
                        $cordovaBluetoothLE.writeQ(params).then(function (obj) {
                            console.log("Write Success : " + JSON.stringify(obj));
                            $rootScope.$broadcast('sendToMenu', 'on');
                            // var bytes = bluetoothle.encodedStringToBytes(obj.value);
                            // var string = bluetoothle.bytesToString(bytes);
                            // console.log(string);
                        }, function (obj) {
                            console.log("Write Error : " + JSON.stringify(obj));
                            if(obj.error == 'isNotConnected' || obj.error == 'isDisconnected'){
                                $rootScope.$broadcast('sendToMenu', 'off');
                                console.log('掉线了......');
                                // $rootScope.$broadcast('disconnected', 'true');
                                $cordovaBluetoothLE.reconnect({
                                    address: _this.address
                                }).then(function (status) {
                                    console.log('断线重新连接成功......');
                                    $rootScope.$broadcast('sendToMenu', 'on');
                                    console.log(status);
                                }, function (error) {
                                    console.log('重新连接失败......');
                                    console.log(error);
                                });
                            }

                        });
                        // }, 1, count);
                    }, time);
                    time += 100; //每次发送了命令后间隔100毫秒

                });

            },
            closeLED: function () {
                var ble_name = JSON.parse(localStorage.getItem(this.address)).name;
                var data;
                if(ble_name.indexOf('QMK-') > -1){
                    data = [[
                        0x8a, //起始码
                        0x00,  //查询当前数据
                        0x00,
                        0x00,
                        0x00,
                        0x00,
                        0x00,
                        0x00,
                        0x00 //结束码
                    ]];

                    /*data = [[
                        '0x8a', //起始码
                        '0x00',  //模式
                        '0x00', //速度
                        '0x00', //亮度
                        '0x01', //倒计时
                        '0xff', //红光
                        '0xff',  //绿光
                        '0xff', //蓝光
                        '0xaf' //结束码
                    ]];*/
                }else{
                    data = [[0x7e, 0x04, 0x04, 0x00, 0xff, 0xff, 0xff, 0x00, 0xef]];
                }

              this.write(data);
            },
            getBLEStatus: function () { //获取蓝牙状态
                // return;
                var ble_name = JSON.parse(localStorage.getItem(this.address)).name;
                var _this = this;
                if(ble_name.indexOf('QMK-') > -1){
                    var ints = new Uint8Array(getCurrentData, getCurrentData.length);
                    var params = {
                        address: this.address,
                        service: this.service,
                        characteristic: this.characteristic,
                        value: $cordovaBluetoothLE.bytesToEncodedString(ints),

                        // value: $cordovaBluetoothLE.bytesToEncodedString($cordovaBluetoothLE.stringToBytes("Hello World")),
                        timeout: 5000
                    };
                    var params1 = {
                        address: this.address,
                        service: this.service,
                        characteristic: this.characteristic,
                        // descriptor: '2901'
                    };
                    if(isiOS){
                        params.type = 'noResponse'
                    }

                    console.log("Write : " + JSON.stringify(params) + ' ' + new Date().getTime());
                    // $cordovaBluetoothLE.write(params).then(function (obj) {
                    $cordovaBluetoothLE.writeQ(params).then(function (obj) {
                        console.log("Write Success : " + JSON.stringify(obj));
                        $rootScope.$broadcast('sendToMenu', 'on');
                        $cordovaBluetoothLE.read(params1).then(function (obj1) { //读取数据
                            console.log("read Success : " + JSON.stringify(obj1));
                            var bytes = bluetoothle.encodedStringToBytes(obj1.value);
                            // var string = bluetoothle.bytesToString(bytes);
                            console.log('读取数据。。。。。。。。。。。');
                            console.log(bytes);
                            // console.log(string);
                        }, function (error) {
                            console.log("read Error : " + JSON.stringify(error));
                        });

                    }, function (obj) {
                        console.log("Write Error : " + JSON.stringify(obj));
                        if(obj.error == 'isNotConnected' || obj.error == 'isDisconnected'){
                            $rootScope.$broadcast('sendToMenu', 'off'); //侧滑菜单的图标变为红色
                            console.log('掉线了......');
                            // $rootScope.$broadcast('disconnected', 'true');
                            $cordovaBluetoothLE.reconnect({
                                address: _this.address
                            }).then(function (status) {
                                console.log('重新连接......');
                                console.log(status);
                                $rootScope.$broadcast('sendToMenu', 'on');
                            }, function (error) {
                                console.log('重新连接失败......');
                                console.log(error);
                            });
                        }

                    });

                }

            },
            isConnect: function (callback) {
                var params = {
                    address: this.address
                };
                $cordovaBluetoothLE.isConnected(params).then(function (obj) {
                    // console.log("Is Connected Success : " + JSON.stringify(obj));
                    callback(true);
                }, function (obj) {
                    // console.log("Is Connected Error : " + JSON.stringify(obj));
                    callback(false);
                });
            },
            isScanning: function (callback) {
                $cordovaBluetoothLE.isScanning().then(function (obj) {
                    // console.log("Is Scanning Success : " + JSON.stringify(obj));
                    callback(obj);
                });
            }
        };
    });
